/**
 * 
 */
package com.geezdata.cps.ttk.core.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.cqrs.command.Command;
import com.geezdata.cps.cqrs.command.bus.CommandBus;
import com.geezdata.cps.sdk3rd.pinduoduo.domain.PinduoduoDDKGoodsPidGenerate;
import com.geezdata.cps.ttk.common.request.CreateOrUpdatePromotionSpaceRequest;
import com.geezdata.cps.ttk.common.response.CreateOrUpdatePromotionSpaceResult;
import com.geezdata.cps.ttk.common.vo.PromotionSpaceReqVO;
import com.geezdata.cps.ttk.domain.domain.PromotionSpace;
import com.geezdata.cps.ttk.domain.domain.Sharer;
import com.geezdata.cps.ttk.integration.ddk.DdkIntegrationService;
import com.geezdata.cps.ttk.mapper.mapper.PromotionSpaceMapper;

/**
 * @author sszheng
 * @date 创建时间：2018年11月1日 下午4:33:02
 *
 */
@Service
public class PromotionSpaceManage {
	
	@Autowired
	private CommandBus commandBus;
	@Autowired
	private Command<CreateOrUpdatePromotionSpaceRequest, CreateOrUpdatePromotionSpaceResult> createOrUpdatePromotionSpaceCommand;
	@Autowired
	private PromotionSpaceMapper promotionSpaceMapper;
	@Autowired
	private DdkIntegrationService ddkIntegerationService;
	
	public PromotionSpace getOrCreatePromotionSpace(Sharer sharer) {
		PromotionSpace promotionSpace = promotionSpaceMapper.selectByOpenId(sharer.getOpenId());
		if(promotionSpace != null) {
			return promotionSpace;
		}
		
		return createSharerPromotionMapping(sharer);
	}
	
	private PromotionSpace createSharerPromotionMapping(Sharer sharer) {
		PinduoduoDDKGoodsPidGenerate promotionSpace = ddkIntegerationService.getPidGenerate(sharer);
		
		CreateOrUpdatePromotionSpaceRequest createOrUpdatePromotionSpaceRequest = convent2CreateOrUpdatePromotionSpaceRequest(promotionSpace, sharer);
		BaseResponse<CreateOrUpdatePromotionSpaceResult> result = commandBus.dispatch(createOrUpdatePromotionSpaceCommand, createOrUpdatePromotionSpaceRequest);
		return promotionSpaceMapper.selectByPrimaryKey(result.getResult().getPromotionSpaceId());
	}

	private CreateOrUpdatePromotionSpaceRequest convent2CreateOrUpdatePromotionSpaceRequest(PinduoduoDDKGoodsPidGenerate promotionSpace, Sharer sharer) {
		CreateOrUpdatePromotionSpaceRequest createOrUpdatePromotionSpaceRequest = new CreateOrUpdatePromotionSpaceRequest();
    	PromotionSpaceReqVO promotionSpaceReqVO = new PromotionSpaceReqVO();
    	promotionSpaceReqVO.setOpenId(sharer.getOpenId());
    	promotionSpaceReqVO.setPlatform("pinduoduo");
    	promotionSpaceReqVO.setPlatformPromotionSpaceId(promotionSpace.getpId());
    	promotionSpaceReqVO.setPlatformPromotionSpaceName(promotionSpace.getpIdName());
    	createOrUpdatePromotionSpaceRequest.setPromotionSpaceReqVO(promotionSpaceReqVO);

		return createOrUpdatePromotionSpaceRequest;
	}
}
